#helper functions

position <- function(lr) {
  l <- sum(lr=="left")
  r <- sum(lr =="right")
  log(r+.5) - log(l+.5)
}  

### modeling function
models <- function(data, treatment, controls = "+left_right + education + sex + age + age_sq"){
  fm_ols <- list()
  
  fm_fe <- list()  
  fm_fe$mod_1 <- as.formula(paste0("proeu", "~", treatment, "|", "country_year"))
  fm_fe$mod_2 <- as.formula(paste0("proeu", "~", treatment, "+left_right" ,"|", "country_year"))
  fm_fe$mod_3 <- as.formula(paste0("proeu", "~", treatment, controls, "|", "country_year"))
  fe <-  lapply(fm_fe, function(x) {
    feols(x, vcov = "cluster", data = data, combine.quick = FALSE)
  })
  fm <- fe  
}

### logit models
logit_models <- function(data, treatment, controls = "+ education + sex + age + age_sq + left_right"){
  fm_fe <- list()  
  fm_fe$mod_1 <- as.formula(paste0("proeu", "~", treatment, "|", "country_year"))
  fm_fe$mod_2 <- as.formula(paste0("proeu", "~", treatment, "+left_right" ,"|", "country_year"))
  fm_fe$mod_3 <- as.formula(paste0("proeu", "~", treatment, controls, "|", "country_year"))
  fe <-  lapply(fm_fe, function(x) {
    feglm(x, vcov = "cluster", data = data, family = binomial("logit"), combine.quick = FALSE)
  })
  fm <- fe  
}
#### table function
coef_rename <- function(modelname) {
  if (modelname == "Keywords"){
    c('Policy-loss (Keywords)',
      'Left-Right',
      'University',
      'Female',
      'Age',
      'Age squared'
      )
  } else if (modelname == "CMPecon"){
    c('Policy-loss (CMPecon)',
      'Left-Right',
      'University',
      'Female',
      'Age',
      'Age squared'
      )
  } else if (modelname == "CMPsocial"){
    c('Policy-loss (CMPsocial)',
      'Left-Right',
      'University',
      'Female',
      'Age',
      'Age squared'
      )
  } else if (modelname == "CMPgen"){
    c('Policy-loss (CMPgen)',
      'Left-Right',
      'University',
      'Female',
      'Age',
      'Age squared'
      )
  } else if (modelname == "LLM"){
    c('Policy-loss (LLM)',
      'Left-Right',
      'University',
      'Female',
      'Age',
      'Age squared'
      )
  } else if (modelname == "Factor"){
    c('Policy-loss (Factor)',
      'Left-Right',
      'University',
      'Female',
      'Age',
      'Age squared'
      )
  } else if (modelname == "extra"){
    c("Intercept",
      'Policy-loss (Factor)',
      'Left-right',
      'University',
      'Female',
      'Age',
      'Age squared',
      'Political discussion',
      'University * Female',
      'Policy-loss (Factor) * Female',
      'Policy-loss (Factor) * University',
      'Policy-loss (Factor) * University * Female'
    )
  } else {
    stop("modelname must be either 'Keywords', 'CMPecon' , 'CMPsocial' , 'CMPgen', 'LLM', 'Factor', 'extra ")
  }
}

results_table <- function(models, modelname, caption, label, outfile){
  texreg::texreg(list(models$mod_1, 
                      models$mod_2, models$mod_3),
                 custom.coef.name = coef_rename(modelname),
                 caption = caption,
                 label = label,
                 include.rsquared = FALSE,
                 include.adjrs = FALSE,
                 include.proj.stats = FALSE, 
                 include.deviance = FALSE,
                 include.pseudors = FALSE,
                 include.loglik = FALSE,
                 custom.gof.rows = list("Cluster st.errors" = c("Country-year", "Country-year", "Country-year")),
                 custom.note = "Robust standard errors in parentences.",
                 sideways =TRUE,
                 scalebox = .8,
                 use.packages = FALSE,dcolum = TRUE,
                 digits = 3,
                 stars = c(0.001, 0.01, 0.05),
                 file = outfile) 
}

extract_treatment <- function(models, treatment, modtype = "model", modelnames = NULL) {
  lapply(seq(models), function(x){
    models[[x]] |> 
      broom::tidy() |> 
      filter(term == treatment)}) |> bind_rows() -> vals
  if(is.null(modelnames)){
  out <-  cbind(vals, modtype)
  } else {
  out <- cbind(vals, modtype,modelnames)
  }
  return(out)
}

###### annual models function
### modeling function
annual_models <- function(data, treatment, controls = "+ education + sex + age + age_sq + left_right", old){
fe  <-as.formula(paste0("proeu", "~", treatment, controls,"|", "ms"))
years <- unique(data$year)
  annual <- lapply(years, function(i) fixest::feols(fe, 
                                                                          data = data, 
                                                                          subset = data$year == i & data$old15 == old,
                                                                          cluster = "ms"))
    extract_treatment(annual, treatment, modtype = years)
}

#### country model function
### modeling function
country_models <- function(data, treatment, controls = "+ education + sex + age + age_sq + left_right", dependent = "proeu"){
  fe  <-as.formula(paste0(dependent, "~", treatment, controls,"|", "year"))
  countries = unique(data$ms)
  country <- lapply(countries, function(i) fixest::feols(fe, 
                                                    data = hh_data, 
                                                    subset = hh_data$ms == i,
                                                    weights = hh_data$weights,
                                                    cluster = "year"))
  extract_treatment(country, treatment, modtype = countries)
}


